<template>
  <div class="app-container">
    <div style="width: 100%; height: 100%; padding: 30px 60px;  border: 1px solid #D6D6D6; background: white;">
      <h2 style="margin-bottom: 50px; font-weight:500; font-size: 32px">补贴处理</h2>
      <el-row :gutter="15">
        <el-form ref="elForm" :model="queryParams" size="medium" label-width="auto" label-position="left">
          <el-col :span="24">
            <el-row>
              <el-col :span="24">
                <el-row>
                </el-row>
              </el-col>
              <el-col :span="24">
                <el-row style="margin-bottom: 22px; display: flex; align-items: center;">
                  <el-col :span="2">
                    <span style="font-weight: 700;">状态：</span>
                  </el-col>
                  <el-col :span="22">
                    <el-button
                      :style="selectedStatus === '全部' ? 'background-color: #97B95C; color: #fff; padding: 7px 50px; border-radius: 24px' : 'background-color: #E8F0DB; color: #333; padding: 7px 50px; border-radius: 24px'"
                      @click="selectStatus('全部')">全部</el-button>
                    <el-button v-show="!(checkRole(['district']) || checkRole(['districtNongji']))"
                      :style="selectedStatus === '审核中' ? 'background-color: #97B95C; color: #fff; padding: 7px 40px; border-radius: 24px' : 'background-color: #E8F0DB; color: #333; padding: 7px 40px; border-radius: 24px'"
                      @click="selectStatus('审核中')">审核中</el-button>
                    <el-button
                      :style="selectedStatus === '待处理' ? 'background-color: #97B95C; color: #fff; padding: 7px 40px; border-radius: 24px' : 'background-color: #E8F0DB; color: #333; padding: 7px 40px; border-radius: 24px'"
                      @click="selectStatus('待处理')">待处理</el-button>
                    <el-button v-show="!(checkRole(['district']) || checkRole(['districtNongji']))"
                      :style="selectedStatus === '异常' ? 'background-color: #97B95C; color: #fff; padding: 7px 50px; border-radius: 24px' : 'background-color: #E8F0DB; color: #333; padding: 7px 50px; border-radius: 24px'"
                      @click="selectStatus('异常')">异常</el-button>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="24">
                <el-row :gutter="10" style="margin-bottom: 10px;">
                  <el-col :span="6">
                    <el-form-item label="身份证号码：" prop="idCard">
                      <el-input v-model="queryParams.idCard" placeholder="请输入身份证号码" clearable :style="{ width: '100%' }"
                        @clear="resetQuery"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="一卡通号码：" prop="bankCard">
                      <el-input v-model="queryParams.bankCard" placeholder="请输入一卡通号码" clearable :style="{ width: '100%' }"
                        @clear="resetQuery"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="checkRole(['town']) || checkRole(['townNongji']) ? 6 : 4">
                    <el-button class="custom-search-btn" @click="handleQuery()">搜索</el-button>
                    <el-button class="custom-reset-btn" @click="resetQuery()">重置</el-button>
                    <el-button v-if="checkRole(['town']) || checkRole(['townNongji'])" type="primary" plain
                      style="padding: 10px 20px;" @click="handleCreate">新建</el-button>
                  </el-col>
                  <el-col :span="3">
                    <el-select v-show="checkRole(['district']) || checkRole(['districtNongji'])"
                      v-model="queryParams.townName" clearable placeholder="请选择乡级" @change="handleTownChange"
                      @clear="handleVillageChange">
                      <el-option v-for="item in townOptions" :key="item.value" :label="item.label" :value="item.label" />
                    </el-select>
                  </el-col>
                  <el-col :span="3">
                    <el-select v-model="queryParams.villageName" clearable placeholder="请选择村级"
                      @change="handleVillageChange" @clear="handleVillageChange">
                      <el-option v-for="item in villageOptions" :key="item.value" :label="item.label"
                        :value="item.label" />
                    </el-select>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-col>
        </el-form>
      </el-row>

      <el-table v-loading="loading" fit :data="subsidyApplicationList" @selection-change="handleSelectionChange" border stripe
        style="width: 100%; height: 600px; overflow-y: auto;">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="工单编号" align="center" prop="appNum" v-if="true" />
        <el-table-column label="申请人" align="center" prop="appyBy"  />
        <el-table-column label="乡" align="center" prop="townName"  />
        <el-table-column label="村" align="center" prop="villageName"  />
        <el-table-column label="身份证号码" align="center" prop="idCard" />
        <el-table-column label="银行卡号码" align="center" prop="bankCard" />
        <el-table-column label="机具名称" align="center" prop="machineName" />
        <el-table-column label="申请时间" align="center" prop="submitDate">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.submitDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="statusShow">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.statusShow" :type="statusTagType(scope.row.statusShow)">{{ scope.row.statusShow
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="当前流程" align="center" prop="nodeName"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleView(scope.row)">查看</el-button>
            <el-button type="text" icon="el-icon-edit" @click="handleVerifiedView(scope.row)"
              v-hasPermi="['machinery:verified:view']">登记</el-button>
            <el-button style="color: red;" type="text" icon="el-icon-edit" @click="showRejectDialog(scope.row)"
              v-hasPermi="['machinery:verified:rejected']">驳回</el-button>
            <el-dialog title="驳回意见" :visible.sync="rejectDialogVisible" width="600px" @close="resetReject">
              <el-form :model="rejectForm" ref="rejectFormRef">
                <el-form-item label="驳回意见" prop="remark"
                  :rules="[{ required: true, message: '请输入驳回意见', trigger: 'blur' }]">
                  <el-input type="textarea" v-model="rejectForm.remark" placeholder="请输入驳回意见" rows="6"
                    style="margin-top: 10px;"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="rejectDialogVisible = false">取消</el-button>
                <el-button type="danger" :loading="rejectLoading" @click="confirmReject(scope.row)">确认驳回</el-button>
              </span>
            </el-dialog>
            <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['subsidy:subsidyApplication:remove']"
            >删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />

      <!-- 添加或修改补贴申请对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="补贴编号" prop="appNum">
            <el-input v-model="form.appNum" placeholder="请输入补贴编号" />
          </el-form-item>
          <el-form-item label="申请人" prop="appyBy">
            <el-input v-model="form.appyBy" placeholder="请输入申请人" />
          </el-form-item>
          <el-form-item label="身份证号码" prop="idCard">
            <el-input v-model="form.idCard" placeholder="请输入身份证号码" />
          </el-form-item>
          <el-form-item label="银行卡号码" prop="bankCard">
            <el-input v-model="form.bankCard" placeholder="请输入银行卡号码" />
          </el-form-item>
          <el-form-item label="村名称" prop="villageName">
            <el-input v-model="form.villageName" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="乡名称" prop="townName">
            <el-input v-model="form.townName" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="提交人" prop="submitBy">
            <el-input v-model="form.submitBy" placeholder="请输入提交人" />
          </el-form-item>
          <el-form-item label="提交时间" prop="submitDate">
            <el-date-picker clearable v-model="form.submitDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择提交时间">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { listComplieHandle, getSubsidyApplication, delSubsidyApplication, addSubsidyApplication, updateSubsidyApplication, rejectSubsidyApplication } from "@/api/machinery/compliehandle";
import { checkRole, checkPermi } from '@/utils/permission'
import { listStrativeArea, getStrativeArea, delStrativeArea, addStrativeArea, updateStrativeArea } from "@/api/subsidy/strativeArea";

export default {
  components: {},
  props: [],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 补贴申请表格数据
      subsidyApplicationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        townName: undefined,
        straName:'滴道区',
        // status: undefined,
        statusShow: undefined,
        villageName: undefined,
      },
      // 状态按钮选中
      selectedStatus: '全部',
      // 村级下拉选项
      options: [],
      // 表单参数
      form: {},
      townOptions: [],
      villageOptions: [],
      // 驳回弹窗相关
      rejectDialogVisible: false,
      rejectForm: {
        remark: ''
      },
      rejectLoading: false,
      appNum: undefined
    };
  },

  computed: {},
  watch: {},
  created() {
    if ((checkRole(['townNongji']) || checkRole(['town']))) {
      this.townName = this.$store.state.user.user.townName;
      this.queryParams.townName = this.townName
      console.log("当前登录角色乡名字", this.townName)
      listStrativeArea({ townName: this.townName }).then(response => {
        console.log("村列表数据展示", response[0].children[0].children)
        this.villageOptions = response[0].children[0].children;
        // if (this.villageOptions.length > 0) {
        //     this.queryParams.villageName = this.villageOptions[0].label; // 或 .value，看你要绑定哪个
        //     // 触发后续查询（可选）
        //     this.handleQuery(); // 如果你想在默认选中后立即查询
        // }
      })
    }
    if (checkRole(['district']) || checkRole(['districtNongji'])) {
      this.straName = '滴道区'
      // this.queryParams.straName = this.straName
      listStrativeArea({ departmentName: '滴道区' }).then(response => {
        this.townOptions = response[0]?.children?.filter(item => item.type === 'town') || [];
        console.log("town", this.townOptions);

        // if (this.townOptions.length > 0) {
        //     this.queryParams.townName = this.townOptions[0].label; // 或 .value，看你要绑定哪个
        //     this.updateVillageOptions()
        //     this.handleQuery(); // 如果你想在默认选中后立即查询
        // }
      })
    }
    this.getList();
  },
  mounted() { },
  methods: {
    checkRole, // 让模板可以访问 checkRole
    // 状态按钮切换
    selectStatus(status) {
      this.selectedStatus = status;
      // 可选：同步筛选条件
      this.queryParams.statusShow = status === '全部' ? undefined : status;
      this.getList();
    },
    // 根据状态返回tag类型
    statusTagType(status) {
      switch (status) {
        case '审核中':
          return 'warning';
        case '待处理':
          return 'primary';
        case '异常':
          return 'danger';
        case '已完成':
          return 'success';
        default:
          return '';
      }
    },
    updateVillageOptions() {
      // 清空当前村庄选择
      this.queryParams.villageName = '';

      if (!this.queryParams.townName) {
        this.villageOptions = [];
        return;
      }

      // 从 townOptions 中找到选中的乡镇
      const selectedTown = this.townOptions.find(town => town.label === this.queryParams.townName);

      // 设置村庄选项为其 children
      this.villageOptions = selectedTown?.children || [];
      // 如果有村庄，自动选中第一个
      if (this.villageOptions.length > 0) {
        this.queryParams.villageName = this.villageOptions[0].label; // 或 .value，看你要绑定哪个
        // 触发后续查询（可选）
        this.handleQuery(); // 如果你想在默认选中后立即查询
      }
    },
    // 村级选择变化时，自动刷新列表
    handleVillageChange() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleTownChange() {
      this.updateVillageOptions()
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询补贴申请列表 */
    getList() {
      this.loading = true;
      listComplieHandle(this.queryParams).then(response => {
        this.subsidyApplicationList = response.rows;
        this.total = response.total;
        this.daichutotal = response.daichutotal
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        appBigType: undefined,
        appType: undefined,
        appNum: undefined,
        appyBy: undefined,
        idCard: undefined,
        bankCard: undefined,
        villageName: undefined,
        townName: undefined,
        status: undefined,
        statusShow: undefined,
        submitBy: undefined,
        submitDate: undefined,
        delFlag: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 列表查看跳转
    handleView(row) {
      console.log("查询", row)
      let path = '';
      if (checkRole(['district', 'districtNongji'])) {
        path = '/machinery/compliehandle/stra/application';
      } else if (checkRole(['townNongji'])) {
        path = '/machinery/compliehandle/application';
      } else {
        this.$modal.msgError(`未赋予权限`)
        path = '/machinery/compliehandle';
      }
      if (path) {
        this.$router.push({
          path,
          query: { id: row.id, node: row.node, status: row.statusShow }
        });
      }

    },
    // 列表新建
    handleVerifiedView(row) {
      console.log("查询", row)
      this.$router.push({
        path: '/machinery/compliehandle/registration',
        query: { id: row.id, node: row.node }
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加补贴申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getSubsidyApplication(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改补贴申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateSubsidyApplication(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addSubsidyApplication(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除补贴申请编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delSubsidyApplication(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('subsidy/subsidyApplication/export', {
        ...this.queryParams
      }, `subsidyApplication_${new Date().getTime()}.xlsx`)
    },
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        // TODO 提交表单
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    /** 新建按钮操作 */
    handleCreate() {
      this.$router.push({
        path: '/machinery/compliehandle/application'
      });
    },
    // 显示驳回弹窗
    showRejectDialog(row) {
      this.rejectDialogVisible = true;
      this.rejectForm.remark = '';
      this.appNum = row.appNum
      console.log("appNum", row.appNum);

    },

    // 重置弹窗内容
    resetReject() {
      this.rejectForm.remark = '';
      this.rejectLoading = false;
    },

    // 确认驳回
    confirmReject(row) {
      this.$refs.rejectFormRef.validate(valid => {
        if (!valid) return;
        this.rejectLoading = true;
        // 调用接口
        rejectSubsidyApplication({
          appNum: this.appNum,
          remark: this.rejectForm.remark
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('驳回成功');
            this.rejectDialogVisible = false;
            // this.$tab.closeOpenPage('/machinery/compliehandle');
            this.getList()
          } else {
            this.$message.error(res.msg || '驳回失败');
          }
        }).catch(() => {
          this.$message.error('驳回失败');
        }).finally(() => {
          this.rejectLoading = false;
        });
      });
    },
  }
}

</script>
<style scoped>
.app-container {
  width: 100%;
  align-items: center;
  /* margin-left: 10%; */
  overflow-x: hidden
    /* border: 1px solid rgb(204, 28, 28); */
}

/* 搜索/重置按钮自定义样式 */
.custom-search-btn {
  background-color: #E8F0DB !important;
  color: #333 !important;
  padding: 10px 20px;
  transition: all 0.2s;
}

.custom-search-btn:hover,
.custom-search-btn:focus {
  background-color: #97B95C !important;
  color: #fff !important;
  border: 1px solid #97B95C !important;
}

.custom-reset-btn {
  background-color: #fff !important;
  color: #333 !important;
  padding: 10px 20px;
  transition: all 0.2s;
}

.custom-reset-btn:hover,
.custom-reset-btn:focus {
  background-color: #E8F0DB !important;
  color: #97B95C !important;
  border: 1px solid #97B95C !important;
}
</style>
